<template>
  <div class="chat-room">
    <!-- 左侧会话列表 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <el-button class="new-chat-btn" type="primary" @click="createNewChat">
          <el-icon><Plus /></el-icon>新对话
        </el-button>
      </div>

      <div class="sidebar-content">
        <div class="search-box">
          <el-input
            v-model="searchText"
            placeholder="搜索对话..."
            :prefix-icon="Search"
            clearable
          />
        </div>

        <div class="chat-list">
          <div v-if="chatList.length === 0" class="empty-list">
            <el-empty description="暂无对话记录" />
          </div>
          <div
            v-else
            v-for="chat in chatList"
            :key="chat.id"
            class="chat-item"
            :class="{ active: currentSession?.id === chat.id }"
            @click="handleSelectSession(chat)"
          >
            <div class="chat-icon">
              <el-icon><ChatRound /></el-icon>
            </div>
            <div class="chat-info">
              <div class="chat-title">{{ chat.title || '新对话' }}</div>
              <div class="chat-meta">{{ formatTime(chat.lastMessageTime) }}</div>
            </div>
            <div class="chat-actions">
              <el-button
                class="action-btn"
                type="text"
                :icon="Edit"
                @click.stop="handleEdit(chat)"
              />
              <el-button
                class="action-btn"
                type="text"
                :icon="Delete"
                @click.stop="handleDelete(chat)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-content">
      <template v-if="currentSession">
        <!-- 聊天消息区域 -->
        <div class="chat-content" ref="chatContentRef">
          <div 
            v-for="msg in messageList" 
            :key="msg.id"
            class="message-item"
            :class="{ 'message-right': msg.role === 'user' }"
          >
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
              <div class="message-time">{{ formatTime(msg.createTime) }}</div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <div class="input-box">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :autosize="{ minRows: 1, maxRows: 4 }"
              placeholder="输入消息，与AI助手对话..."
              resize="none"
              @keyup.enter="handleSend"
            />
            <div class="input-actions">
              <div class="left-actions">
                <span class="input-tips">按 Enter 发送 / Shift + Enter 换行</span>
              </div>
              <div class="right-actions">
                <span class="model-tag">Spark4.0 Ultra</span>
                <el-button
                  type="primary"
                  :loading="sending"
                  :disabled="!inputMessage.trim()"
                  @click="handleSend"
                >
                  发送
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </template>

      <div v-else-if="!isNewSession" class="welcome-screen">
        <div class="welcome-content">
          <div class="ai-avatar">
            <el-icon :size="48"><Service /></el-icon>
          </div>
          <p>您好！我是您的AI心理咨询助手，让我们开始对话吧！</p>
          <div class="quick-starts">
            <div class="quick-starts-title">您可以这样问我：</div>
            <div class="suggestion-list">
              <div
                v-for="(suggestion, index) in suggestions"
                :key="index"
                class="suggestion-item"
                @click="handleSuggestionAndCreate(suggestion)"
              >
                <el-icon><ChatLineRound /></el-icon>
                <span>{{ suggestion }}</span>
              </div>
            </div>
          </div>
          
          <el-button type="primary" size="large" @click="createNewChat">开始对话</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-room {
  display: flex;
  height: calc(100vh - 100px);  // 调整高度，减少一点
  margin: 12px;  // 调整边距
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .sidebar {
    width: 280px;
    background: #fff;
    border-right: 1px solid #e8e8e8;
    display: flex;
    flex-direction: column;
    
    .sidebar-header {
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      
      .new-chat-btn {
        width: 100%;
        height: 44px;
        border-radius: 10px;
        font-size: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
      }
    }

    .sidebar-content {
      flex: 1;
      overflow: hidden;  // 防止内容溢出
      
      .search-box {
        padding: 12px 16px;
        
        :deep(.el-input__wrapper) {
          border-radius: 10px;
          background: #f5f5f5;
          box-shadow: none;
          
          &:hover {
            background: #f0f0f0;
          }
        }
      }

      .chat-list {
        height: 100%;  // 确保列表占满剩余空间
        overflow-y: auto;
        padding: 8px;
        
        .chat-item {
          display: flex;
          align-items: center;
          padding: 12px;
          border-radius: 10px;
          cursor: pointer;
          transition: all 0.3s;
          margin-bottom: 4px;
          
          &:hover {
            background: #f5f5f5;
          }
          
          &.active {
            background: var(--el-color-primary-light-9);
            
            .chat-icon {
              color: var(--el-color-primary);
            }
          }
          
          .chat-icon {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            background: #f0f0f0;
            margin-right: 12px;
          }
          
          .chat-info {
            flex: 1;
            min-width: 0;
            
            .chat-title {
              font-size: 14px;
              margin-bottom: 4px;
              color: #333;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .chat-meta {
              font-size: 12px;
              color: #999;
            }
          }
          
          .chat-actions {
            display: none;  // 默认隐藏
            gap: 4px;
          }
          
          &:hover .chat-actions {
            display: flex;  // 悬停时显示
          }
        }
      }
    }
  }

  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;  // 防止内容溢出
    background: #fff;
    position: relative;
    
    .chat-content {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      
      .message-item {
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        
        &.message-right {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          
          .message-content {
            background: #ecf5ff;
          }
        }
        
        .message-content {
          max-width: 70%;
          padding: 12px 16px;
          background: #f4f6f8;
          border-radius: 8px;
          
          .message-text {
            font-size: 14px;
            line-height: 1.5;
            word-break: break-word;
          }
          
          .message-time {
            font-size: 12px;
            color: #909399;
            margin-top: 4px;
          }
        }
      }
    }
    
    .chat-input {
      padding: 20px;
      background: #fff;
      border-top: 1px solid #e8e8e8;
      
      .input-box {
        background: #f9f9f9;
        border: 1px solid #e0e0e0;
        border-radius: 12px;
        padding: 12px 16px;
        
        :deep(.el-textarea__inner) {
          background: transparent;
          border: none;
          padding: 0;
          font-size: 14px;
          line-height: 1.6;
          resize: none;
          box-shadow: none;
          
          &:focus {
            box-shadow: none;
          }
        }
        
        .input-actions {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 8px;
          padding-top: 8px;
          border-top: 1px solid #eee;
          
          .left-actions {
            .input-tips {
              font-size: 12px;
              color: #909399;
            }
          }
          
          .right-actions {
            display: flex;
            align-items: center;
            gap: 12px;
            
            .model-tag {
              font-size: 12px;
              color: #666;
              background: #eee;
              padding: 2px 8px;
              border-radius: 4px;
            }
            
            .el-button {
              margin: 0;
              height: 32px;
              padding: 0 16px;
              border-radius: 6px;
            }
          }
        }
      }
    }
  }
}

.text-red {
  color: var(--el-color-danger);
}

// 自定义滚动条样式
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
  
  &:hover {
    background: #ccc;
  }
}

// 添加欢迎界面样式
.welcome-screen {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: #fff;
  
  .welcome-content {
    max-width: 600px;
    text-align: center;
    
    .ai-avatar {
      width: 80px;
      height: 80px;
      margin: 0 auto 20px;
      background: var(--el-color-primary-light-9);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--el-color-primary);
    }
    
    h2 {
      font-size: 24px;
      color: #333;
      margin-bottom: 12px;
    }
    
    p {
      font-size: 16px;
      color: #666;
      margin-bottom: 20px;  // 减少间距
    }
    
    .quick-starts {
      margin-bottom: 40px;
      
      .quick-starts-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 16px;
        text-align: left;  // 左对齐
        padding-left: 12px;  // 添加一点左边距
      }
      
      .suggestion-list {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 12px;
        
        .suggestion-item {
          padding: 12px 16px;
          background: #f5f7fa;
          border-radius: 8px;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 8px;
          transition: all 0.3s;
          
          &:hover {
            background: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
            transform: translateY(-2px);
          }
          
          .el-icon {
            font-size: 18px;
          }
          
          span {
            font-size: 14px;
          }
        }
      }
    }
    
    .el-button {
      padding: 12px 36px;
      font-size: 16px;
    }
  }
}

.test-result-link {
  color: #409eff;
  text-decoration: none;
}

.test-result-link:hover {
  text-decoration: underline;
}
</style>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus,
  ChatRound,
  More,
  Search,
  Service,
  User,
  ChatLineRound,
  CopyDocument,
  InfoFilled,
  Connection,
  Position,
  Message,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import type { AIChatSession, AIChatMessage } from '@/types/ai-chat'
import { 
  getAIChatSessions,
  createAIChatSession,
  getAIChatMessages,
  sendAIChatMessage,
  deleteAIChatSession,
  renameAIChatSession
} from '@/api/ai-chat'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const route = useRoute()
const router = useRouter()

// 从路由获取会话信息
const sessionId = ref(route.query.sessionId as string)
const isNewSession = ref(route.query.new === 'true')

// 基础数据
const searchText = ref('')
const chatList = ref<AIChatSession[]>([
  // 添加一条模拟数据
  {
    id: 1,
    title: '示例对话',
    lastMessage: '您好！我是您的AI心理咨询助手',
    lastMessageTime: '2024-03-08 16:00:00',
    status: 'ACTIVE'
  }
])
const currentSession = ref<AIChatSession | null>(null)
const messageList = ref<AIChatMessage[]>([
  // 添加模拟对话数据
  {
    id: 1,
    sessionId: 1,
    role: 'assistant',
    content: '您好！我是您的AI心理咨询助手。我可以帮助您缓解压力、改善情绪，让我们开始对话吧！',
    createTime: '2024-03-08 16:00:00',
    emotionScore: 0.8,
    riskLevel: 'LOW_RISK'
  },
  {
    id: 2,
    sessionId: 1,
    role: 'user',
    content: '最近感觉压力很大，该怎么办？',
    createTime: '2024-03-08 16:01:00',
    emotionScore: 0.4,
    riskLevel: 'MEDIUM_RISK'
  },
  {
    id: 3,
    sessionId: 1,
    role: 'assistant',
    content: '我理解您现在的感受。面对压力是很正常的，让我们一起来分析和缓解：\n\n1. 首先，深呼吸几次，让自己平静下来\n2. 尝试列出让您感到压力的具体事项\n3. 适当运动，比如散步或瑜伽\n4. 保持规律的作息时间\n5. 与信任的人分享您的感受\n\n您愿意和我详细说说是什么让您感到压力吗？',
    createTime: '2024-03-08 16:01:30',
    emotionScore: 0.7,
    riskLevel: 'LOW_RISK'
  }
])
const inputMessage = ref('')
const sending = ref(false)
const chatContentRef = ref<HTMLElement | null>(null)

// 计算属性

const currentEmotionScore = computed(() => {
  const lastMessage = messageList.value[messageList.value.length - 1]
  return lastMessage?.emotionScore || 0.5
})


// 方法定义
const loadChatList = async () => {
  try {
    const { data } = await getAIChatSessions()
    chatList.value = data
  } catch (error) {
    ElMessage.error('加载会话列表失败')
  }
}

const createNewChat = async (testResultId?: number) => {
  try {
    const { data: session } = await createAIChatSession(testResultId)
    chatList.value.unshift(session)
    currentSession.value = session
    
    // 加载消息（包括欢迎消息）
    const { data } = await getAIChatMessages(session.id)
    messageList.value = data
    
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    ElMessage.error('创建会话失败')
  }
}

const handleSelectSession = async (session: AIChatSession) => {
  currentSession.value = session
  messageList.value = [] // 先清空消息
  
  try {
    // 加载该会话的所有消息
    const { data } = await getAIChatMessages(session.id)
    messageList.value = data
    
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    ElMessage.error('加载消息失败')
  }
}

const handleSend = async (e?: KeyboardEvent): Promise<boolean> => {
  // 如果是键盘事件，且是 Shift+Enter，则插入换行
  if (e?.shiftKey && e.key === 'Enter') {
    e.preventDefault()
    inputMessage.value += '\n'
    return false
  }
  
  const session = currentSession.value
  if (!session?.id || !inputMessage.value.trim() || sending.value) {
    return false
  }
  
  const userContent = inputMessage.value.trim()
  inputMessage.value = ''
  
  // 立即添加用户消息到界面
  const userMessage: AIChatMessage = {
    id: Date.now(),
    sessionId: session.id,
    role: 'user',
    content: userContent,
    createTime: new Date().toISOString()
  }
  messageList.value.push(userMessage)
  
  sending.value = true
  try {
    // 发送消息
    const { data } = await sendAIChatMessage({
      sessionId: session.id,
      content: userContent
    })
    
    // 更新用户消息的真实ID并添加AI回复
    const userIndex = messageList.value.findIndex(msg => msg.content === userContent)
    if (userIndex !== -1) {
      messageList.value[userIndex].id = data.id - 1
    }
    messageList.value.push(data)
    
    nextTick(() => {
      scrollToBottom()
    })
    
    return true
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败')
    return false
  } finally {
    sending.value = false
  }
}




// 工具函数
const formatTime = (time?: string) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

const scrollToBottom = () => {
  const content = chatContentRef.value
  if (content) {
    content.scrollTop = content.scrollHeight
  }
}



// 添加建议问题列表
const suggestions = [
  '最近感觉压力很大，该怎么办？',
  '如何改善睡眠质量？',
  '怎样缓解考试焦虑？',
  '如何与他人更好地沟通？',
  '感觉很孤独，该怎么办？',
  '如何提高自信心？'
]

const handleSuggestionAndCreate = async (suggestion: string) => {
  try {
    // 1. 创建新会话
    const { data: session } = await createAIChatSession()
    if (!session?.id) {
      throw new Error('创建会话失败')
    }
    
    // 2. 更新前端状态
    chatList.value.unshift(session)
    currentSession.value = session
    messageList.value = [] // 先清空消息列表
    
    // 3. 等待一下确保欢迎消息已经创建
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 4. 加载包含欢迎消息的消息列表
    const { data: initialMessages } = await getAIChatMessages(session.id)
    messageList.value = initialMessages || []
    
    // 5. 发送用户消息
    const userMessage: AIChatMessage = {
      id: Date.now(),
      sessionId: session.id,
      role: 'user',
      content: suggestion,
      createTime: new Date().toISOString()
    }
    messageList.value.push(userMessage)
    
    // 6. 发送到后端并获取 AI 回复
    sending.value = true
    try {
      const { data: aiMessage } = await sendAIChatMessage({
        sessionId: session.id,
        content: suggestion
      })
      
      // 7. 更新消息列表
      const userIndex = messageList.value.findIndex(msg => 
        msg.role === 'user' && msg.content === suggestion
      )
      if (userIndex !== -1) {
        messageList.value[userIndex].id = aiMessage.id - 1
      }
      messageList.value.push(aiMessage)
      
      nextTick(() => {
        scrollToBottom()
      })
    } finally {
      sending.value = false
    }
    
  } catch (error) {
    console.error('快捷提问失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}



// 添加复制功能

// 修改会话操作处理方法的类型

// 在 script setup 中添加这两个方法
const handleEdit = async (chat: AIChatSession) => {
  try {
    const { value: newTitle } = await ElMessageBox.prompt('', {
      title: '编辑会话名称',
      inputValue: chat.title,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => {
        if (!value.trim()) return '名称不能为空'
        return true
      }
    })
    
    if (newTitle && newTitle !== chat.title) {
      try {
        // 调用后端 API 更新标题
        await renameAIChatSession(chat.id, newTitle.trim())
        
        // 更新成功后再更新前端数据
        chat.title = newTitle.trim()
        // 如果是当前会话，也更新当前会话的标题
        if (currentSession.value?.id === chat.id) {
          currentSession.value.title = newTitle.trim()
        }
        ElMessage.success('修改成功')
      } catch (error) {
        console.error('更新标题失败:', error)
        ElMessage.error('更新失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作取消')
    }
  }
}

const handleDelete = async (chat: AIChatSession) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个会话吗？',
      '提示',
      {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
    )
    
    try {
      // 先调用后端 API 删除
      await deleteAIChatSession(chat.id)
      
      // API 调用成功后再更新前端状态
      const index = chatList.value.findIndex(s => s.id === chat.id)
      if (index > -1) {
        chatList.value.splice(index, 1)
      }
      
      // 如果是当前会话，清空显示
      if (currentSession.value?.id === chat.id) {
        currentSession.value = null
        messageList.value = []
      }
      
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作取消')
    }
  }
}

// 格式化消息内容，处理测试结果链接
const formatMessage = (content: string) => {
  // 匹配测试结果链接格式
  const testResultPattern = /\[查看我的心理测试结果\]\(#(.*?)\)/
  const match = content.match(testResultPattern)
  
  if (match) {
    // 将链接转换为可点击的样式
    return content.replace(
      testResultPattern,
      `<a class="test-result-link" href="${match[1]}" target="_blank">查看我的心理测试结果</a>`
    )
  }
  
  // 普通文本消息，处理换行
  return content.replace(/\n/g, '<br>')
}

// 初始化方法
const init = async () => {
  // 加载会话列表
  const { data } = await getAIChatSessions()
  chatList.value = data || []
  
  // 如果有会话ID，直接加载该会话
  if (sessionId.value) {
    const session = chatList.value.find(
      s => s.id.toString() === sessionId.value
    )
    if (session) {
      currentSession.value = session
      const { data: messages } = await getAIChatMessages(parseInt(sessionId.value))
      messageList.value = messages || []
      nextTick(() => {
        scrollToBottom()
      })
    }
  }
}

// 初始化
onMounted(async () => {
  await init()
})

// 监听路由变化
watch(
  () => route.query.sessionId,
  async (newId) => {
    if (newId) {
      sessionId.value = newId as string
      await init()
    }
  }
)
</script> 